#include "c_logger.h"
#include "logger.h"
#include <map>
#include <mutex>
#include <cstdarg>
#include <cstring>

// 使用std命名空间
using namespace multi_sink;

// 存储日志记录器实例的映射
static std::map<logger_t, std::shared_ptr<Logger>> logger_map;
static std::mutex logger_map_mutex;

extern "C"
{

    // 创建日志记录器实例
    logger_t create_logger(const char *tag)
    {
        auto logger = Logger::createLogger(tag);
        if (!logger)
        {
            return nullptr;
        }

        std::lock_guard<std::mutex> lock(logger_map_mutex);
        logger_t instance = reinterpret_cast<logger_t>(logger.get());
        logger_map[instance]         = logger;
        return instance;
    }

    // 销毁日志记录器实例
    void destroy_logger(logger_t logger)
    {
        if (!logger)
        {
            return;
        }

        std::lock_guard<std::mutex> lock(logger_map_mutex);
        auto it = logger_map.find(logger);
        if (it != logger_map.end())
        {
            it->second->destroy();
            logger_map.erase(it);
        }
    }

    // 辅助函数：记录实例消息
    static void log_message(logger_t logger, const char *level, const char *format, va_list args)
    {
        if (!logger)
        {
            return;
        }

        std::lock_guard<std::mutex> lock(logger_map_mutex);
        auto it = logger_map.find(logger);
        if (it == logger_map.end())
        {
            return;
        }

        // 格式化消息
        char buffer[1024];
        vsnprintf(buffer, sizeof(buffer), format, args);

        // 根据级别记录日志
        if (strcmp(level, "info") == 0)
        {
            it->second->info("{}", buffer);
        }
        else if (strcmp(level, "warn") == 0)
        {
            it->second->warn("{}", buffer);
        }
        else if (strcmp(level, "error") == 0)
        {
            it->second->error("{}", buffer);
        }
    }

    // 实例信息日志记录
    void log_info(logger_t logger, const char *format, ...)
    {
        va_list args;
        va_start(args, format);
        log_message(logger, "info", format, args);
        va_end(args);
    }

    // 实例警告日志记录
    void log_warn(logger_t logger, const char *format, ...)
    {
        va_list args;
        va_start(args, format);
        log_message(logger, "warn", format, args);
        va_end(args);
    }

    // 实例错误日志记录
    void log_error(logger_t logger, const char *format, ...)
    {
        va_list args;
        va_start(args, format);
        log_message(logger, "error", format, args);
        va_end(args);
    }

}  // extern "C"